// 单例模式 示例

use lazy_static::lazy_static;
use std::sync::{Arc, Mutex, Once};
use once_cell::sync::OnceCell;
// use std::cell::OnceCell;

struct Signleton01 {
    name: String,
}

// 构建静态宏
lazy_static! {
    static ref INSTANCE: Mutex<Signleton01> = Mutex::new(Signleton01 {
        name: String::from("")
    });
}

impl Signleton01 {
    // 返回静态 struct 的指针
    pub fn get_instance() -> &'static Mutex<Self> {
        return &INSTANCE;
    }

    pub fn set_name(data: String) {
        Signleton01::get_instance().lock().unwrap().name = data
    }

    pub fn get_name(&self) -> &String {
        return &self.name;
    }
}

#[derive()]
struct Signleton02 {
    name: String,
}

impl Signleton02 {
    fn new() -> Arc<Mutex<Self>> {
        Arc::new(Mutex::new(Self {
            name: String::new(),
        }))
    }

    fn get_instance() -> Arc<Mutex<Self>> {
        static INSTANCE: OnceCell<Arc<Mutex<Signleton02>>> = OnceCell::new();
       return INSTANCE.get_or_init(||{
                   Self::new()
               }).clone();
    }

    fn get_instance2() -> Arc<Mutex<Self>>{
        static mut INSTANCE: Option<Arc<Mutex<Signleton02>>> = None;

        unsafe {
            INSTANCE.get_or_insert_with(||{
                Self::new()
            }).clone()
        }
    }

    //  fn new() -> Arc<Mutex<Self>> {
    //     Arc::new(Mutex::new( Self { name: String::from("")}))
    // }

    //  fn get_instance() -> Arc<Mutex<Self>> {
    //     static INSTANCE: OnceCell<Arc<Mutex<Self>>> = OnceCell::new();
    //     return INSTANCE.get_or_init(Self::new());
    // }
}
